package GUILayer;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;

import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

import ControlLayer.AgencyCtr;
import ModelLayer.Agency;

public class AgencyGUI extends JPanel implements ActionListener {

	private static final long serialVersionUID = 1L;
	private AgencyCtr agencyCtr;
	private DefaultTableModel agencyTableModel;
	private JScrollPane tableScrollPane;
	private JPanel tablePanel;
	private DefaultTableModel tableModel;
	private JTable table;
	private JPanel agencyInfoPanel;
	private JPanel choicePanel;

	private JTextField textField_agencyId;
	private JTextField txt_Search;
	private JTextField textField_name;
	private JTextField textField_phone;
	private JTextField textField_email;
	private JTextField textField_country;
	private JTextField textField_address;
	private JTextField textField_discountGroup;

	private JButton btnSave;
	private JButton btnCreate;

	private JButton btnClear;
	private JButton btnDelete;

	public AgencyGUI() {

		agencyCtr = new AgencyCtr();
		initialize();
	}

	public void initialize() {
		this.setLayout(new BorderLayout());
		tablePanel = new JPanel();
		this.add(tablePanel, BorderLayout.CENTER);
		tablePanel.setBorder(BorderFactory.createTitledBorder("All Agencies"));
		tablePanel.setLayout(new BorderLayout());

		JPanel searchPanel = new JPanel();
		txt_Search = new JTextField();
		searchPanel.add(txt_Search);
		txt_Search.addKeyListener(new KeyAdapter() {
			public void keyReleased(KeyEvent arg0) {
				showAllAgency();
			}
		});
		txt_Search.setColumns(70);
		tablePanel.add(searchPanel, BorderLayout.NORTH);

		GroupLayout gl_searchPanel = new GroupLayout(searchPanel);
		gl_searchPanel.setHorizontalGroup(gl_searchPanel.createParallelGroup(
				Alignment.LEADING).addComponent(txt_Search));
		gl_searchPanel.setVerticalGroup(gl_searchPanel.createParallelGroup(
				Alignment.LEADING).addGroup(
				gl_searchPanel
						.createSequentialGroup()
						.addGap(5)
						.addComponent(txt_Search, GroupLayout.PREFERRED_SIZE,
								GroupLayout.DEFAULT_SIZE,
								GroupLayout.PREFERRED_SIZE)));
		searchPanel.setLayout(gl_searchPanel);

		addTable();
		showAllAgency();

		// show agency info view

		JPanel showAgencyPanel = new JPanel();
		this.add(showAgencyPanel, BorderLayout.EAST);
		showAgencyPanel.setLayout(new BorderLayout());
		showAgencyPanel.setBorder(BorderFactory.createTitledBorder("Agency"));

		agencyInfoPanel = new JPanel();
		JLabel lblagencyId = new JLabel("Agency Id: ");
		JLabel lblname = new JLabel("Name: ");
		JLabel lblphone = new JLabel("Phone: ");
		JLabel lblemail = new JLabel("Email: ");
		JLabel lblcountry = new JLabel("Country: ");
		JLabel lbladdress = new JLabel("Address: ");
		JLabel lbldiscountgroup = new JLabel("Discount Group Id: ");

		textField_agencyId = new JTextField();
		textField_agencyId.setEditable(false); // Id is not able to change
		textField_name = new JTextField();
		textField_phone = new JTextField();
		textField_email = new JTextField();
		textField_country = new JTextField();
		textField_address = new JTextField();
		textField_discountGroup = new JTextField();
		textField_discountGroup.setColumns(40);

		GroupLayout gl = new GroupLayout(agencyInfoPanel);
		agencyInfoPanel.setLayout(gl);
		agencyInfoPanel.setBorder(BorderFactory.createTitledBorder("Info"));
		gl.setAutoCreateGaps(true);
		gl.setAutoCreateContainerGaps(true);

		gl.setHorizontalGroup(gl
				.createSequentialGroup()
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(lblagencyId)
								.addComponent(lblname).addComponent(lblphone)
								.addComponent(lblemail)
								.addComponent(lblcountry)
								.addComponent(lbladdress)
								.addComponent(lbldiscountgroup))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.LEADING)
								.addComponent(textField_agencyId)
								.addComponent(textField_name)
								.addComponent(textField_phone)
								.addComponent(textField_email)
								.addComponent(textField_country)
								.addComponent(textField_address)
								.addComponent(textField_discountGroup)));
		gl.setVerticalGroup(gl
				.createSequentialGroup()
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblagencyId)
								.addComponent(textField_agencyId))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblname)
								.addComponent(textField_name))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblphone)
								.addComponent(textField_phone))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblemail)
								.addComponent(textField_email))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lblcountry)
								.addComponent(textField_country))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lbladdress)
								.addComponent(textField_address))
				.addGroup(
						gl.createParallelGroup(GroupLayout.Alignment.BASELINE)
								.addComponent(lbldiscountgroup)
								.addComponent(textField_discountGroup)));

		showAgencyPanel.add(agencyInfoPanel, BorderLayout.NORTH);

		choicePanel = new JPanel();
		choicePanel.setLayout(new FlowLayout());
		btnCreate = new JButton("Create");
		btnDelete = new JButton("Delete");
		btnSave = new JButton("Save");
		btnClear = new JButton("Clear");

		choicePanel.add(btnCreate);

		choicePanel.add(btnSave);
		choicePanel.add(btnDelete);
		choicePanel.add(btnClear);
		showAgencyPanel.add(choicePanel, BorderLayout.CENTER);

		btnCreate.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (!textField_agencyId.getText().isEmpty()) {
					JOptionPane.showMessageDialog(null,
							"Please clear fields before creating new one",
							"Error", JOptionPane.ERROR_MESSAGE);
				} else {
					int dgId;
					if (textField_discountGroup.getText().isEmpty())
						dgId = 0;
					else
						dgId = Integer.parseInt(textField_discountGroup
								.getText());
					try {
						agencyCtr.insertAgency(textField_name.getText(),
								textField_phone.getText(),
								textField_email.getText(),
								textField_country.getText(),
								textField_address.getText(), dgId);
					} catch (Exception e1) {
						JOptionPane.showMessageDialog(null,
								"Discount group not found", "Error",
								JOptionPane.ERROR_MESSAGE);
					}
					JOptionPane.showMessageDialog(null,
							"The agency is created", "Create Agency",
							JOptionPane.INFORMATION_MESSAGE);
					cleanTextField();
					showAllAgency();
				}

			}
		});

		btnSave.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (textField_agencyId.getText().isEmpty()) {
					JOptionPane
							.showMessageDialog(
									null,
									"Please select a agency before saving editing information",
									"Error", JOptionPane.ERROR_MESSAGE);
				} else {
					try {
						int dgId;
						if (textField_discountGroup.getText().isEmpty())
							dgId = 0;
						else
							dgId = Integer.parseInt(textField_discountGroup
									.getText());
						agencyCtr.updateAgency(
								Integer.parseInt(textField_agencyId.getText()),
								textField_name.getText(),
								textField_phone.getText(),
								textField_email.getText(),
								textField_country.getText(),
								textField_address.getText(), dgId);
						JOptionPane.showMessageDialog(null,
								"The agency info is saved", "Update Agency",
								JOptionPane.INFORMATION_MESSAGE);
						cleanTextField();
						showAllAgency();
					} catch (Exception a) {
						JOptionPane.showMessageDialog(null,
								"Please input correct values", "Error",
								JOptionPane.ERROR_MESSAGE);
					}
				}
			}
		});

		btnClear.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				cleanTextField();
			}
		});

		btnDelete.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (textField_agencyId.getText().isEmpty()) {
					JOptionPane.showMessageDialog(null,
							"Please select a agency", "Error",
							JOptionPane.ERROR_MESSAGE);
				} else {
					int reply = JOptionPane.showConfirmDialog(null,
							"Do you want to delete this agency?",
							"Delete Agency", JOptionPane.YES_NO_OPTION,
							JOptionPane.WARNING_MESSAGE);
					if (reply == JOptionPane.YES_OPTION) {
						try {
							if (agencyCtr.deleteAgency(Integer
									.parseInt(textField_agencyId.getText())) == -1)
								JOptionPane
										.showMessageDialog(
												null,
												"Fail to delete agency, because it associated with other objects",
												"Error",
												JOptionPane.ERROR_MESSAGE);
							JOptionPane.showMessageDialog(null,
									"The agency is deleted", "Delete Agency",
									JOptionPane.INFORMATION_MESSAGE);
							cleanTextField();
							showAllAgency();
						} catch (Exception c) {
							JOptionPane.showMessageDialog(null,
									"Fail to delete discount", "Error",
									JOptionPane.ERROR_MESSAGE);
						}
					}
				}
			}
		});

		Border color2 = BorderFactory.createLineBorder(Color.DARK_GRAY);
		Border raisedetched2 = BorderFactory
				.createEtchedBorder(EtchedBorder.RAISED);
		TitledBorder title2;
		title2 = BorderFactory.createTitledBorder(color2, "Agency Info");
		agencyInfoPanel.setBorder(title2);

		gl.setAutoCreateGaps(true);
		gl.setAutoCreateContainerGaps(true);

	}

	public void addTable() {
		tableModel = new DefaultTableModel();
		tableModel.addColumn("Id");
		tableModel.addColumn("Name");
		tableModel.addColumn("Phone");
		tableModel.addColumn("Email");
		tableModel.addColumn("Country");

		tableScrollPane = new JScrollPane();
		table = new JTable(tableModel);
		table.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
		table.setAutoCreateRowSorter(true);

		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				int row = table.rowAtPoint(e.getPoint());
				if (e.getClickCount() == 1) {
					showAgency(Integer.valueOf((Integer) table.getValueAt(row,
							0)));

				}
			}
		});

		tablePanel.add(tableScrollPane, BorderLayout.CENTER);
		tableScrollPane.setViewportView(table);
	}

	public void showAgency(int agencyId) {
		Agency agency = agencyCtr.getAgency(agencyId);
		textField_agencyId.setText(Integer.toString(agency.getId()));
		textField_address.setText(agency.getAddress());
		textField_country.setText(agency.getCountry());
		textField_email.setText(agency.getEmail());
		textField_phone.setText(agency.getPhone());
		textField_name.setText(agency.getName());
		// TODO
		String dgId = "";
		if (agency.getDiscountGroup().getId() != 0) {
			dgId = Integer.toString(agency.getDiscountGroup().getId());
		}
		textField_discountGroup.setText(dgId);

	}

	public void showAllAgency() {
		String searchFilter = txt_Search.getText();
		tableModel.setRowCount(0);
		ArrayList<Agency> agencies = agencyCtr.getAllAgency();

		for (Agency agency : agencies) {
			if (((Integer) agency.getId()).toString().toLowerCase()
					.contains(searchFilter.toLowerCase())
					|| agency.getName().toLowerCase()
							.contains(searchFilter.toLowerCase())) {
				tableModel.addRow(new Object[] { agency.getId(),
						agency.getName(), agency.getPhone(), agency.getEmail(),
						agency.getCountry() });
			}
		}

	}

	public void cleanTextField() {

		txt_Search.setText("");
		textField_agencyId.setText("");
		textField_name.setText("");
		textField_phone.setText("");
		textField_email.setText("");
		textField_address.setText("");
		textField_country.setText("");
		textField_discountGroup.setText("");
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		JComboBox cb = (JComboBox) e.getSource();
		String list = (String) cb.getSelectedItem();

	}
}
